<template>
  <el-card class="box-card">
    <div slot="header">
      <span v-if="isEdit == true">编辑商品</span>
      <span v-else>添加商品</span>
    </div>
    <el-form ref="ruleForm" v-loading.body="loading" label-width="80px" :model="goods" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="goods.title" @keyup.enter.native="save" />
      </el-form-item>
      <el-form-item label="序号" prop="priority">
        <el-input v-model="goods.priority" type="number" placeholder="越小越前" @keyup.enter.native="save" />
      </el-form-item>
      <el-form-item label="热卖推荐" prop="isRecommend">
        <el-radio-group v-model="goods.isRecommend">
          <el-radio-button label="true">推荐</el-radio-button>
          <el-radio-button label="false">不推荐</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-cascader v-model="treeValue" expand-trigger="click" :options="categoryTree" :change-on-select="true" :props="props" placeholder="选择分类" clearable @change="handleItemChange" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="goods.price" @keyup.enter.native="save" />
      </el-form-item>
      <el-form-item label="首页海报" prop="isBanner">
        <el-radio-group v-model="goods.isBanner">
          <el-radio-button label="true">显示</el-radio-button>
          <el-radio-button label="false">不显示</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-loading.body="bannerUploading" label="海报图">
        <el-upload action="api/file/upload" :data="tokenObject" :auto-upload="true" name="file" list-type="picture-card" :show-file-list="false" :on-success="bannerUploadSuccess" :before-upload="bannerBeforeUpload">
          <img v-if="goods.bannerUrl" :src="goods.bannerUrl" class="thumb">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="商品图" prop="thumb">
        <el-upload action="api/file/upload" :data="tokenObject" name="file" :on-success="thumbUploadSuccess" :on-preview="thumbHandlePreview" list-type="picture-card" :on-remove="thumbHandleRemove" :before-upload="thumbBeforeUpload" :file-list="goods.thumb">
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <el-dialog v-model="dialogVisible" title="图片预览" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="描述图" prop="detail">
        <el-upload action="api/file/upload" :data="tokenObject" name="file" :on-success="detailUploadSuccess" :on-preview="detailHandlePreview" list-type="picture-card" :on-remove="detailHandleRemove" :before-upload="detailBeforeUpload" :file-list="goods.detail">
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <el-dialog v-model="dialogVisible" title="图片预览" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import * as goods from '@/api/goods'
import * as category from '@/api/category'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      bannerUploading: false,
      isEdit: false,
      categoryTree: [], // 处理过后的tree
      tokenObject: { token: getToken() },
      props: {
        // cascader props
        value: '_id',
        label: 'title',
        children: 'children'
      },
      treeValue: [],
      goods: {
        title: '',
        price: '1',
        category: '',
        bannerUrl: '',
        thumb: [],
        detail: [],
        isBanner: false,
        isRecommend: false
      },
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        category: [{
          required: true,
          message: '请选择分类',
          trigger: 'blur'
        }],
        price: [{
          required: true,
          message: '请输入价格',
          trigger: 'blur'
        }],
        priority: [{
          required: true,
          message: '请输入序号',
          trigger: 'blur'
        }],
        thumb: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!this.goods.thumb.length) {
              callback(new Error('请上传商品主图'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        detail: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!this.goods.detail.length) {
              callback(new Error('请上传商品描述图片'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  created: function() {
    new Promise((resolve, reject) => {
      category.list().then(response => {
        // 递归
        var { tree } = require('../../utils/utils')
        this.categoryTree = tree(response.data, '')
        resolve(response.data)
      })
    }).then((categoryObjects) => {
      // 如果是编辑
      if (this.$route.query._id) {
        console.log(this.$route.query._id)
        this.isEdit = true
        // 加载商品数据
        goods.detail({ _id: this.$route.query._id }).then(response => {
          console.log(response)
          this.goods = response.data
          this.goods.price = this.goods.price.toString()
          this.goods.priority = this.goods.priority.toString()
          // 递归
          var { findAncestors } = require('../../utils/utils')
          // 还有找到一直向上推进的父类
          var treeValue = findAncestors(categoryObjects, this.goods.category)
          this.treeValue = treeValue.reverse()
        })
      }
    })
  },
  methods: {
    bannerBeforeUpload: function() {
      this.bannerUploading = true
    },
    bannerUploadSuccess: function(res) {
      this.goods.bannerUrl = res.data.url
      this.bannerUploading = false
    },
    handleItemChange: function(val) {
      this.goods.category = val.slice(-1).toString()
    },
    thumbUploadSuccess: function(res, file, fileList) {
      this.goods.thumb.push(res.data)
    },
    thumbBeforeUpload: function(file) {
      var { uploadLimit } = require('../../utils/utils')
      return uploadLimit(file, (error) => {
        this.$message.error(error)
      })
      // uploadLimit(file) && this.$message.error(uploadLimit(file));
      // return !uploadLimit(file);
    },
    thumbHandleRemove(file, images) {
      this.goods.thumb = images
    },
    thumbHandlePreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    detailUploadSuccess: function(res, file, fileList) {
      this.goods.detail.push(res.data)
    },
    detailBeforeUpload: function(file) {
      var { uploadLimit } = require('../../utils/utils')
      return uploadLimit(file, (error) => {
        this.$message.error(error)
      })
      // uploadLimit(file) && this.$message.error(uploadLimit(file));
      // return !uploadLimit(file);
    },
    detailHandleRemove(file, images) {
      this.goods.detail = images
    },
    detailHandlePreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    save: function() {
      // console.log(this.category);
      // return;
      // debugger;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 验证通过
          this.loading = true
          goods.save(this.goods).then(response => {
            // 输出服务端返回
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: response.msg,
                duration: 500,
                onClose: () => {
                  this.loading = false
                  // that.$router.push({name: 'goodsList'});
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
              this.loading = false
            }
          })
        }
      })
    }
  }
}
</script>
<style>
body {
    font-family: Helvetica, sans-serif;
}
</style>
